<template>
  <div v-if="loading" style="text-align: center;padding: 50px;">
    <a-spin></a-spin>
  </div>
  <entity-view v-else form-item-width="50%" @submit="submit" ref="form" :model="productionInfo" class="custom-modal">
    <div class="subtitle">
      <a-form-model-item  :wrapper-col="{ span: 24 }">
        <a-radio-group v-model="defaultChecked" @change="changeProdList">
          <a-radio v-for="(item,index) in this.prodList"  :key="index" :value="index" :disabled="item.disabled" >
            {{item.prodName}}
          </a-radio>
        </a-radio-group>

      </a-form-model-item>
      <a-form-model-item :wrapper-col="{ span: 24 }" v-if="productionInfo.prodCode === 'DF'&&flag=='add'">
        <form-item label="是否全产品统一费率"  @change="setUnitedFee" v-model="unitedFeeFlag" prop="unitedFeeFlag" input-type="radioGroup" :options="[{value:'Y',label:'是'},{value:'N',label:'否'}]" ></form-item>
      </a-form-model-item>
    </div>

    <dev class="sub-content-flex" v-if="this.unitedFeeFlag==='Y'">
      <a-table :columns="feeRateColumns" :dataSource="mchntFeeInfoList" rowKey="id" :pagination="false">
        <template slot="feeInputMode" slot-scope="text, record">
          <a-select v-model="record.feeInputMode">
            <a-select-option value="1">手工输入按比率</a-select-option>
            <a-select-option value="2">手工输入按固定金额</a-select-option>
            <a-select-option value="3">手工输入按比率+封顶值</a-select-option>
          </a-select>
        </template>
        <template slot="feeRate" slot-scope="text, record">
          <a-input type="number" v-model="record.feeRate" :disabled="record.feeInputMode === '2'" min="0"></a-input>
        </template>

        <template slot="feeCappingAmt" slot-scope="text, record">
          <a-input type="number" v-model="record.feeCappingAmt" disabled
                   v-if="record.feeInputMode == '1'" min="0"></a-input>
          <a-input type="number" v-model="record.feeFixedAmt" :disabled="record.feeInputMode === '1'"
                   v-if="record.feeInputMode == '2'" min="0"></a-input>
          <a-input type="number" v-model="record.feeCappingAmt" :disabled="record.feeInputMode === '1'"
                   v-if="record.feeInputMode == '3'" min="0"></a-input>
        </template>
      </a-table>
    </dev>
    <div class="sub-content-flex">
      <a-table
        ref="TableInfo"
        tableLayout="auto"
        :rowKey="
            (record, index) => {
              return index;
            }
          "
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          hideDefaultSelections:true,
          onChange: onSelectChange,
          getCheckboxProps: (record) => ({
           props: {
                disabled: this.operatorType!=='add'&&this.operatorType!=='edit',
    　　　　　},
  　　　　}),
         }"
        :pagination="false"
        :columns="columns"
        :dataSource="dataSource"
      >
        <template slot="operation" slot-scope="text, record">
          <a-icon
            type="setting"
            theme="twoTone"
            twoToneColor="#4a9ff5"
            @click="edit(record)"
            v-if="operatorType === 'edit'||operatorType === 'add'"
            title="配置"
          ></a-icon>

          <a-icon
            type="eye"
            theme="twoTone"
            twoToneColor="#4a9ff5"
            @click="view(record)"
            title="查看"
          ></a-icon>
        </template>
      </a-table>
    </div>
    <div class="sub-content-flex">
      <form-item label="停用原因" prop="mchntStopReason" v-model="productionInfo.mchntStopReason" :disabled="this.operationContext.operatorType !== 'stop'" v-if="this.operationContext.operatorType === 'stop' || this.operationContext.operatorType === 'view'" input-type="select" :options="[
      {value: '1', name: '黑名单商户'},
      {value: '2', name: '3个月无交易'},
      {value: '3', name: '12个月无交易'},
      {value: '4', name: '经营异常'},
      {value: '5', name: '涉嫌电信诈骗'},
      {value: '6', name: '其它'},
      {value: '7', name: '证件到期'},
    ]"></form-item>
      <form-item label="注销原因" prop="mchntCancelReason" v-model="productionInfo.mchntCancelReason" :disabled="this.operationContext.operatorType !== 'cancel'" input-type="textarea" v-if="this.operationContext.operatorType === 'cancel' || this.operationContext.operatorType === 'view'"></form-item>

      <form-item label="审核拒绝原因" prop="auditRefuseReason" v-model="productionInfo.auditRefuseReason" :disabled="this.operationContext.operatorType !== 'chk'" input-type="textarea" v-if="this.operationContext.operatorType === 'chk' || this.operationContext.operatorType === 'view'"></form-item>

    </div>
    <div class="btn-wrapper">
      <a-button type="primary" @click="previous">上一步</a-button>
      <a-button type="primary" html-type="submit" v-if="operatorType !== 'view'&&operatorType !== 'chk'">提交审批</a-button>
      <a-button type="primary" @click="checkMchntProd('back')" v-if="operatorType === 'chk'">审批退回</a-button>
      <a-button type="primary" @click="checkMchntProd('pass')" v-if="operatorType === 'chk'">审批通过</a-button>
    </div>
    <a-modal
      v-model="mchntProdDtl.visiable"
      :title="mchntProdDtl.modalTitle"
      width="1200px"
      @ok="mchntProdDtlSubmit"
      :maskClosable="false"
      :footer="isHideFoot?null:undefined"
    >
      <mchnt-prod-dtl ref="mchntProdDtl" />
    </a-modal>

  </entity-view>
</template>

<script>
import EntityView from '../../../../components/common/entityView/EntityView'
import FormItem from '../../../../components/common/entityView/FormItem'
import MchntProdDtl from './MchntProdDtl'
import AFormModelItem from "ant-design-vue/es/form-model/FormItem";
export default {
  name: 'ProductionInfoForm',
  components: {AFormModelItem, EntityView, FormItem, MchntProdDtl},
  provide: function () {
    return {
      merchantProdInfoContext: this
    }
  },
  inject: ['merchantBaseInfoContext', 'operationContext'],
  data: function () {
    return {
      loading: false,
      isHideFoot: false,
      productionInfo: {},
      mchntProdDtlCfgList: [],
      mchntBaseProdListOrg: [],
      unitedFeeFlag:'N',
      mchntAttr:'',
      pageInfo: {},
      operatorType: "add",
      optFlag: "add",
      flag: "add",
      dataSource: [],
      selectedRowKeys: [],
      columns:[
        {
          title: "产品代码",
          dataIndex: "baseProdCode",
        },
        {
          title: "产品名称",
          dataIndex: "baseProdName",
        },
        {
          title: "产品描述",
          dataIndex: "baseProdDesc",
        },
        {
          title: "操作",
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" },
        },
      ],
      mchntFeeInfoList: [
        {
          feeTypeName:"全产品同一费率",
          feeInputMode: "1",
          feeRate: "",
          feeCappingAmt: "",
          customRender: "",
        }
      ],
      feeRateColumns: [
        {
          title: '卡种/业务',
          dataIndex: 'feeTypeName'
        },
        {
          title: '费率输入方式',
          dataIndex: 'feeInputMode',
          scopedSlots: {customRender: 'feeInputMode'}
        },
        {
          title: '费率比率(‰)',
          dataIndex: 'feeRate',
          scopedSlots: {customRender: 'feeRate'}
        },
        {
          title: '封顶值(元)/固定金额(元)',
          dataIndex: 'feeCappingAmt',
          scopedSlots: {customRender: 'feeCappingAmt'}
        },
      ],
      mchntProdUnitedFee:{},
      mchntProdDtl:{
        visiable:false,
        modalTitle:"查看"
      },
      prodList:[],
      defaultChecked:0
    }
  },
  mounted () {
    this.getPageInfo()
  },
  methods: {

    /**
     * 提交审核
     * @returns {Promise<boolean>}
     */
    async submit () {
      if(this.operatorType === 'edit' || this.operatorType === 'add'||this.operatorType === 'stop'||this.operatorType === 'use'||this.operatorType === 'cancel'){
        const params = Object.assign({}, this.productionInfo);
        var mchntBaseProdList=[];

        if(this.unitedFeeFlag==='Y'&&this.optFlag==='add'&&this.productionInfo.prodCode==='DF'){
          this.mchntFeeInfoList;
          this.mchntProdUnitedFee=this.mchntFeeInfoList[0];

          if(this.mchntProdUnitedFee.feeInputMode===""){
            this.$message.error('请选择费率输入方式！')
            return;
          }

          if(this.mchntProdUnitedFee.feeInputMode==="1"){
            if(this.mchntProdUnitedFee.feeRate===""){
              this.$message.error('请输入费率比率！')
              return;
            }
          }

          if(this.mchntProdUnitedFee.feeInputMode==="2"){
            if(this.mchntProdUnitedFee.feeFixedAmt===""){
              this.$message.error('请输入固定金额！')
              return;
            }
          }

          if(this.mchntProdUnitedFee.feeInputMode==="3"){
            if(this.mchntProdUnitedFee.feeCappingAmt===""){
              this.$message.error('请输入固定金额！')
              return;
            }
            if(this.mchntProdUnitedFee.feeRate===""){
              this.$message.error('请输入费率比率！')
              return;
            }
          }

          this.mchntProdUnitedFee.baseProdCode    = "00";
          this.mchntProdUnitedFee.feeType         = "99";

          params.mchntProdUnitedFee=this.mchntProdUnitedFee;
        }

        this.dataSource.map(i => {
          var mchntBaseProd = {};
          if (this.optFlag == "add") {
            if (params.prodCode === 'DF') {

              if (i.baseProdPath === 'Y') {
                mchntBaseProd.baseProdCode = i.baseProdCode;
                mchntBaseProd.oprType = "01";
                for (var i = 0; i < this.mchntProdDtlCfgList.length; i++) {

                  var bProdInfo = this.mchntProdDtlCfgList[i];
                  if (bProdInfo.baseProdCode == mchntBaseProd.baseProdCode && bProdInfo.prodCode == params.prodCode) {

                    mchntBaseProd = bProdInfo.mchntBaseProdList[0];
                    mchntBaseProd.baseProdCode = bProdInfo.baseProdCode;
                    mchntBaseProd.oprType = "01";
                    params.wechatChannelId = bProdInfo.wechatChannelId;
                    params.alipayChannelId = bProdInfo.alipayChannelId;
                  }
                }

                mchntBaseProdList.push(mchntBaseProd);
              }
            } else {
              mchntBaseProd.baseProdCode = i.baseProdCode;
              mchntBaseProd.oprType = "01";
              for (var i = 0; i < this.mchntProdDtlCfgList.length; i++) {
                var bProdInfo = this.mchntProdDtlCfgList[i];
                if (bProdInfo.baseProdCode == mchntBaseProd.baseProdCode && bProdInfo.prodCode == params.prodCode) {
                  mchntBaseProd = bProdInfo.mchntBaseProdList[0];
                  mchntBaseProd.baseProdCode = bProdInfo.baseProdCode;
                  mchntBaseProd.oprType = "01";
                  params.wechatChannelId = bProdInfo.wechatChannelId;
                  params.alipayChannelId = bProdInfo.alipayChannelId;
                }
              }
              mchntBaseProdList.push(mchntBaseProd);
            }
          } else {
            if (i.baseProdPath === 'Y') {
              mchntBaseProd.baseProdCode = i.baseProdCode;
              mchntBaseProd.oprType = '02';
              if (this.optFlag == "upd") {
                params.prodCode = "DF";
              }
              for (var i = 0; i < this.mchntProdDtlCfgList.length; i++) {
                var bProdInfo = this.mchntProdDtlCfgList[i];
                if (bProdInfo.baseProdCode == mchntBaseProd.baseProdCode) {
                  mchntBaseProd = bProdInfo.mchntBaseProdList[0];
                  
                  mchntBaseProd.oprType = "02";
                  mchntBaseProd.baseProdCode = bProdInfo.baseProdCode;
                  params.wechatChannelId = bProdInfo.wechatChannelId;
                  params.alipayChannelId = bProdInfo.alipayChannelId;
                }
              }
              mchntBaseProdList.push(mchntBaseProd);
            }
          }
        })

        params.mchntBaseProdList = mchntBaseProdList;

        

        if(params.prodCode==""){
          this.$message.error("请选择商户产品");
          return false
        }


        if(this.optFlag=="add" || this.optFlag=="upd"){
          if(this.mchntAttr == "01" || this.mchntAttr == "11") { //实体特约商户或实体兼网络特约商户
            var checkFla = false;
            for (var j = 0; j < params.mchntBaseProdList.length; j++) {

              var bPCode = params.mchntBaseProdList[j].baseProdCode;
              if(bPCode == "01" || bPCode == "02" || bPCode == "03"){ //选择pos或条码
                checkFla = true;
                break;
              }
            }
            if(checkFla == false){
              this.$message.error("商户属性为实体特约商户或实体兼网络特约商户，请选择刷卡支付或收/付款扫码！");
              return false;
            }
          }
        }


        //修改时比较，新增时不需比较
        if(params.optFlag=="upd"){
          //新增
          
          var mchntBaseProdList=[];
          var mchntBaseProdListAdd = this.compareBaseProd(this.mchntBaseProdListOrg,params.mchntBaseProdList,"01");
          var mchntBaseProdListDel = this.compareBaseProd(params.mchntBaseProdList,this.mchntBaseProdListOrg,"04");
          /*for(var i=0;i<mchntBaseProdListAdd.length;i++){
                      param.mchntBaseProdList.push(mchntBaseProdListAdd[i]);

                  }*/
          for(var j=0;j<mchntBaseProdListDel.length;j++){
            params.mchntBaseProdList.push(mchntBaseProdListDel[j]);

          }
        }



        if(params.prodCode==""){
          this.$message.error("请选择产品后再提交?");
          return false;
        }
        if(params.prodCode=="DF"&&params.mchntBaseProdList.length==0){
          this.$message.error( "请选择产品后再提交？");
          return false;
        }
        if(this.optFlag=="upd"&&params.mchntBaseProdList.length==0){
          this.$message.error("请选择产品后再提交？");
          return false;
        }

        if (this.optFlag == "stop") {
          if (!this.productionInfo.mchntStopReason || this.productionInfo.mchntStopReason == "") {
            this.$message.error("请输入停用原因");
            return false;
          } else {
            params.mchntStopReason =this.productionInfo.mchntStopReason;
          }
        }
        if (this.optFlag == "cancel") {
          if (!this.productionInfo.mchntCancelReason || this.productionInfo.mchntCancelReason == "") {
            this.$message.error("请输入注销原因");
            return false;
          } else {
            params.mchntCancelReason = this.productionInfo.mchntCancelReason.trim();
          }
        }

        if(this.optFlag=="upd"){
          params.prodCode="DF";
        }
        params.optFlag = {add: `add`, edit: `upd`, view: `view`, use: `use`, stop: `stop`, cancel: `cancel`,chk: `chk`}[this.operatorType]
        params.instId = this.merchantBaseInfoContext.query.instId
        params.mchntNo = this.operationContext.beanInfo.mchntNo
        params.unitedFeeFlag = this.unitedFeeFlag
        const res = await this.$post('/admin/mcmp/bMchntBaseInfo/editMchntProd', params)
        if (res.data.code === "100000") {
          this.$message.success('保存成功！')
          this.$emit("submit");
          return true
        } else if(res.data.code === "111111"){
          this.$message.success('商户注销审批通过！')
          this.$emit("submit");
          return true
        }else {
          this.$message.error(res.data.message)
          return false
        }
      } else {
        this.$emit("submit");
      }
    },


    changeProdList (e) {
      this.productionInfo = this.prodList[e.target.value]
      this.dataSource = this.prodList[e.target.value].baseProdInfoList;
    },

    setUnitedFee (e) {
      this.unitedFeeFlag = e.target.value;

    },


    /**
     * 加载商户业务产品
     * @returns {Promise<void>}
     */
    async getPageInfo () {
      try {
        this.operatorType = this.operationContext.operatorType;
        let optFlag = {add: `add`, edit: `upd`, view: `view`, use: `use`, stop: `stop`, cancel: `cancel`,chk: `chk`}[this.operatorType]
        const param = {
          optFlag: optFlag,
          instId: this.merchantBaseInfoContext.query.instId,
          mchntNo: this.operationContext.beanInfo.mchntNo
        }
        this.loading = true;
        const res = await this.$get('/admin/mcmp/bMchntBaseInfo/editMchntProd',param);

        this.loading = false;
        this.optFlag = res.data.optFlag;
        this.flag = res.data.flag;
        
        if(this.optFlag !== 'add'){
          this.productionInfo = res.data;
          this.dataSource = this.productionInfo.prodList;
          this.productionInfo.disabled = true;
          this.prodList = [];
          this.prodList.push(this.productionInfo);
        }else{
          this.prodList = res.data.prodList.map(item=>{
            item.disabled = false
            return item;
          });
          this.productionInfo = this.prodList[0];
          this.dataSource = this.prodList[0].baseProdInfoList;
        }
        this.productionInfo.mchntNo = this.operationContext.beanInfo.mchntNo
        let selected = []
        this.dataSource.forEach((i,index) => {
          
          if(i.baseProdPath === 'Y'){
            this.mchntBaseProdListOrg.push(i);
            selected.push(index);
          }
        })
        
        this.selectedRowKeys = selected;
        this.productionInfo.auditRefuseReason=res.data.auditRefuseReason;
        this.productionInfo.mchntStopReason=res.data.mchntStopReason;
        this.productionInfo.mchntCancelReason=res.data.mchntCancelReason;
        this.mchntAttr=res.data.mchntAttr;
      } catch (e) {
        console.error(e)
      }
    },

    previous () {
      this.operationContext.tabActiveKey = 'settleInfo';
    },

    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
      this.dataSource.forEach((i,index) => {
        i.baseProdPath = 'N';
        if(selectedRowKeys.indexOf(index) != -1){
          i.baseProdPath = 'Y';
        }
      })
    },

    /**
     * 产看产品配置
     * @param record
     * @returns {Promise<void>}
     */
    async view(record) {
      this.mchntFeeInfoList;
      this.mchntProdDtl.visiable = true;
      this.mchntProdDtl.modalTitle = "查看";
      this.isHideFoot = true;
      //判断是否为全产品同一费率
      if(this.unitedFeeFlag==='Y'&&this.optFlag==='add'&&this.productionInfo.prodCode==='DF'){
        this.mchntFeeInfoList;
        this.mchntProdUnitedFee=this.mchntFeeInfoList[0];

        if(this.mchntProdUnitedFee.feeInputMode===""){
          this.$message.error('请选择费率输入方式！')
          this.mchntProdDtl.visiable = false;
        }

        if(this.mchntProdUnitedFee.feeInputMode==="1"){
          if(this.mchntProdUnitedFee.feeRate===""){
            this.$message.error('请输入费率比率！')
            this.mchntProdDtl.visiable = false;
          }
        }

        if(this.mchntProdUnitedFee.feeInputMode==="2"){
          if(this.mchntProdUnitedFee.feeFixedAmt===""){
            this.$message.error('请输入固定金额！')
            this.mchntProdDtl.visiable = false;
          }
        }

        if(this.mchntProdUnitedFee.feeInputMode==="3"){
          if(this.mchntProdUnitedFee.feeCappingAmt===""){
            this.$message.error('请输入固定金额！')
            this.mchntProdDtl.visiable = false;
          }
          if(this.mchntProdUnitedFee.feeRate===""){
            this.$message.error('请输入费率比率！')
            this.mchntProdDtl.visiable = false;
          }
        }
      }
      this.$nextTick(() => {
        this.$refs.mchntProdDtl.getBeanInfo(record,this.productionInfo.prodCode, this.merchantBaseInfoContext.query.instId, this.operationContext.beanInfo.mchntNo, "view",this.optFlag,this.mchntProdUnitedFee,this.unitedFeeFlag)
      })
    },

    /**
     * 配置产品
     * @param record
     * @returns {Promise<void>}
     */
    async edit(record) {
      this.mchntProdDtl.visiable = true;
      //判断是否为全产品同一费率
      if(this.unitedFeeFlag==='Y'&&this.optFlag==='add'&&this.productionInfo.prodCode==='DF'){
        this.mchntFeeInfoList;
        this.mchntProdUnitedFee=this.mchntFeeInfoList[0];

        if(this.mchntProdUnitedFee.feeInputMode===""){
          this.$message.error('请选择费率输入方式！')
          this.mchntProdDtl.visiable = false;
        }

        if(this.mchntProdUnitedFee.feeInputMode==="1"){
          if(this.mchntProdUnitedFee.feeRate===""){
            this.$message.error('请输入费率比率！')
            this.mchntProdDtl.visiable = false;
          }
        }

        if(this.mchntProdUnitedFee.feeInputMode==="2"){
          if(this.mchntProdUnitedFee.feeFixedAmt===""){
            this.$message.error('请输入固定金额！')
            this.mchntProdDtl.visiable = false;
          }
        }

        if(this.mchntProdUnitedFee.feeInputMode==="3"){
          if(this.mchntProdUnitedFee.feeCappingAmt===""){
            this.$message.error('请输入固定金额！')
            this.mchntProdDtl.visiable = false;
          }
          if(this.mchntProdUnitedFee.feeRate===""){
            this.$message.error('请输入费率比率！')
            this.mchntProdDtl.visiable = false;
          }
        }
      }










      this.mchntProdDtl.modalTitle = "配置";
      this.isHideFoot = false;
      this.$nextTick(() => {
        this.$refs.mchntProdDtl.getBeanInfo(record,this.productionInfo.prodCode,this.merchantBaseInfoContext.query.instId,this.operationContext.beanInfo.mchntNo,"upd",this.optFlag,this.mchntProdUnitedFee,this.unitedFeeFlag)
      })
    },

    mchntProdDtlSubmit(){
      const res = this.$refs.mchntProdDtl.submit()
      if(res){
        this.mchntProdDtl.visiable = false
      }
    },


    /**
     * 商户审核
     * @param type
     * @returns {Promise<boolean>}
     */
    async checkMchntProd(type) {
      const params = Object.assign({}, this.productionInfo)
      params.mchntBaseProdList=[];
      this.dataSource.map(i => {
        if (i.baseProdPath === 'Y') {
          params.mchntBaseProdList.push(i);
        }
      });
      params.optFlag = type;
      params.instId = this.merchantBaseInfoContext.query.instId
      params.mchntNo = this.operationContext.beanInfo.mchntNo
      params.unitedFeeFlag = this.unitedFeeFlag
      params.auditRefuseReason=this.productionInfo.auditRefuseReason;

      if (type === 'back') {
        if(params.auditRefuseReason===""){
          this.$message.error('请输入拒绝原因！')
          return;
        }
      }
      const res = await this.$post('/admin/mcmp/bMchntBaseInfo/editMchntProd', params)
      if (res.data.code === "100000") {
        this.$message.success('保存成功！')
        this.$emit("submit");
        return true
      } else {
        this.$message.error(res.data.message)
        return false
      }


    },


    /**
     * 比较原子产品 新增、修改、删除,原子产品列表界面只有新增、删除
     * @param prodInfoOrg
     * @param prodInfo
     * @param optType
     */
    compareBaseProd(mchntBaseProdListOrg, mchntBaseProdList, optType) {
      var baseProdList = [];
      for (var i = 0; i < mchntBaseProdList.length; i++) {
        var baseProdInfo = mchntBaseProdList[i];
        var add = true;
        var baseProdInfoOrg = {};
        for (var j = 0; j < mchntBaseProdListOrg.length; j++) {
          baseProdInfoOrg = mchntBaseProdListOrg[j];
          if (baseProdInfo.baseProdCode == baseProdInfoOrg.baseProdCode) {
            add = false;
          }
        }
        if (add) {
          baseProdInfo.oprType = optType;
          baseProdList.push(baseProdInfo);
        }
      }
      return baseProdList;
    }


  }
}
</script>

<style scoped>
.btn-wrapper{
  padding: 10px;
  width: 100%;
  text-align: center;
}
.subtitle {
  width: 100%;
  font-size: 16px;
  margin-bottom: 10px;
  padding: 0 10px;
}

.sub-content-flex {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}

.sub-content-block {
  display: block;
  flex-wrap: wrap;
  width: 100%;
  padding: 0 10px;
}
.custom-modal .ant-calendar-picker{
    width: 100%;
}
.ant-table-wrapper{
  width: 100%;
}
</style>
